import Vue from 'vue'
class Filter {
    install(Vue) {

        /**
         * 10/13位时间戳转为北京时间
         * timestamp 时间戳
         * format 时间格式
         * 如需要返回'2019年01月01日'，format传"yyyy年MM月dd日"
         */

        Vue.filter('dateFormat', function (timestamp, format = "yyyy-MM-dd hh:mm:ss") {
            if (timestamp === null || timestamp === undefined) {
                return ''
            }
            //10位时间戳转13位
            if (String(timestamp).length == 10) {
                timestamp += '000'
            }
            //时间戳转数字类型
            timestamp = Number(timestamp)
            //时间戳传入date对象
            const realDate = new Date(timestamp)

            //给单位数前面补0
            function timeFormat(num) {
                return `${num}`.padStart(2, '0')
            }
            let date = [
                ["M+", timeFormat(realDate.getMonth() + 1)],
                ["d+", timeFormat(realDate.getDate())],
                ["h+", timeFormat(realDate.getHours())],
                ["m+", timeFormat(realDate.getMinutes())],
                ["s+", timeFormat(realDate.getSeconds())],
                ["q+", Math.floor((realDate.getMonth() + 3) / 3)],
                ["S+", realDate.getMilliseconds()],
            ]
            let reg1 = /(y+)/i.exec(format)
            // console.log(reg1[0])
            if (reg1) {
                format = format.replace(reg1[1], (realDate.getFullYear() + '').substring(4 - reg1[1].length))
            }
            for (let i = 0; i < date.length; i++) {
                let k = date[i][0]
                let v = date[i][1]

                let reg2 = RegExp("(" + k + ")").exec(format)
                if (reg2) {
                    format = format.replace(reg2[1], reg2[1].length == 1 ?
                        v : ("00" + v).substring(("" + v).length))
                }
            }
            return format
        })
    }
}

Vue.use(new Filter())